package com.shu.mqtt;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URISyntaxException;

import org.fusesource.hawtdispatch.Dispatch;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;

public class MqttPublish {
	
	static String topic = "apk/heartbeat";
	
    public static void main(String[] args) throws URISyntaxException, Exception {
        MQTT mqtt = new MQTT();
        mqtt.setHost("tcp://192.168.1.15:1882");
        mqtt.setUserName("admin");
        mqtt.setPassword("public");
        mqtt.setKeepAlive((short)2);
        mqtt.setClientId("1");
        mqtt.setCleanSession(false);
        mqtt.setDispatchQueue(Dispatch.createQueue("mqtt.test.aaa"));
        final CallbackConnection connection = mqtt.callbackConnection();
        connection.listener(new ConnListener());
        
        
//        connection.publish(topic, payload, qos, retain, cb);
        
        connection.connect(new ConnCallback());
        File file = new File("C:\\Users\\mzj\\Desktop\\android6.0.8.apk");
        System.out.println(file.length());
        String msg = getFileToSt(file);
        System.out.println(msg);
        for(int i=0;i<1;i++){
        	   // Send a message to a topic
            connection.publish(topic, msg.getBytes("utf8"),
            QoS.AT_LEAST_ONCE, true, new Callback<Void>() {
            public void onSuccess(Void v) {
            	System.out.println(" publish success");
            }
           
            public void onFailure(Throwable value) {
            	System.out.println("publish fail");
            }
            });
            Thread.sleep(100*5);
        }
       

    }
    
	public static String getFileToSt(File file) throws Exception {
		FileInputStream in = new FileInputStream(file);
		// size 为字串的长度 ，这里一次性读完
		int size = in.available();
		byte[] buffer = new byte[size];
		in.read(buffer);
		in.close();
		return new String(buffer, "utf8");
		// 为什么不一次性把buffer得大小取出来呢？为什么还要写入到bos中呢？ return new(buffer,"UTF-8") 不更好么?
		// return new String(bos.toByteArray(),"UTF-8");
	}
    
    public static byte[] getFileToByte(File file) {
        byte[] by = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return by;
    }
}